/**
 * 流程状态样式管理器
 * 负责根据流程实例数据和节点状态动态设置流程图的样式
 */

// 节点状态枚举
export enum NodeStatus {
  COMPLETED = 'COMPLETED',      // 已完成
  RUNNING = 'RUNNING',          // 当前执行
  PENDING = 'PENDING',          // 等待执行
  WAITING = 'WAITING',          // 等待条件
  SKIPPED = 'SKIPPED',          // 已跳过
  CANCELLED = 'CANCELLED'       // 已取消
}

// 连线状态枚举
export enum EdgeStatus {
  COMPLETED = 'COMPLETED',      // 已完成
  ACTIVE = 'ACTIVE',            // 激活状态
  INACTIVE = 'INACTIVE',        // 非激活状态
  PENDING = 'PENDING'           // 等待状态
}

// 节点类型枚举
export enum NodeType {
  START = 'start',
  END = 'end',
  USER_TASK = 'userTask',
  SERVICE_TASK = 'serviceTask',
  GATEWAY = 'gateway',
  PARALLEL_GATEWAY = 'parallelGateway',
  INCLUSIVE_GATEWAY = 'inclusiveGateway',
  EXCLUSIVE_GATEWAY = 'exclusiveGateway',
  SUB_PROCESS = 'subProcess',
  CC = 'cc'
}

// 样式配置接口
export interface StatusStyleConfig {
  backgroundColor: string
  borderColor: string
  color: string
  borderWidth?: number
  borderStyle?: string
}

// 连线样式配置接口
export interface EdgeStyleConfig {
  stroke: string
  strokeWidth: number
  strokeDasharray: string
  animated: boolean
}

// 节点状态样式映射
const NODE_STATUS_STYLES: Record<NodeStatus, StatusStyleConfig> = {
  [NodeStatus.COMPLETED]: {
    backgroundColor: '#f6ffed',
    borderColor: '#52c41a',
    color: '#389e0d'
  },
  [NodeStatus.RUNNING]: {
    backgroundColor: '#e6f7ff',
    borderColor: '#409eff',
    color: '#1890ff'
  },
  [NodeStatus.PENDING]: {
    backgroundColor: '#fff7e6',
    borderColor: '#faad14',
    color: '#d48806'
  },
  [NodeStatus.WAITING]: {
    backgroundColor: '#fff2e8',
    borderColor: '#fa8c16',
    color: '#d46b08'
  },
  [NodeStatus.SKIPPED]: {
    backgroundColor: '#f9f0ff',
    borderColor: '#722ed1',
    color: '#531dab'
  },
  [NodeStatus.CANCELLED]: {
    backgroundColor: '#fff2f0',
    borderColor: '#ff4d4f',
    color: '#cf1322'
  }
}

// 连线状态样式映射
const EDGE_STATUS_STYLES: Record<EdgeStatus, EdgeStyleConfig> = {
  [EdgeStatus.COMPLETED]: {
    stroke: '#52c41a',
    strokeWidth: 3,
    strokeDasharray: '0',
    animated: false
  },
  [EdgeStatus.ACTIVE]: {
    stroke: '#fa8c16',
    strokeWidth: 3,
    strokeDasharray: '8,4',
    animated: true
  },
  [EdgeStatus.INACTIVE]: {
    stroke: '#8c8c8c',
    strokeWidth: 2,
    strokeDasharray: '8,4',
    animated: false
  },
  [EdgeStatus.PENDING]: {
    stroke: '#d9d9d9',
    strokeWidth: 2,
    strokeDasharray: '8,4',
    animated: false
  }
}

// 节点类型默认样式
const NODE_TYPE_DEFAULT_STYLES: Record<string, Partial<StatusStyleConfig>> = {
  [NodeType.START]: {
    backgroundColor: '#f6ffed',
    borderColor: '#52c41a',
    color: '#389e0d'
  },
  [NodeType.END]: {
    backgroundColor: '#fff2f0',
    borderColor: '#f5222d',
    color: '#cf1322'
  },
  [NodeType.GATEWAY]: {
    backgroundColor: '#fff7e6',
    borderColor: '#faad14',
    color: '#d48806'
  }
}

/**
 * 流程状态样式管理器
 */
export class ProcessStatusStyleManager {
  get graphData(): any {
    return this._graphData;
  }

  set graphData(value: any) {
    this._graphData = value;
  }
  get processInstance(): any {
    return this._processInstance;
  }

  set processInstance(value: any) {
    this._processInstance = value;
  }
  private _processInstance: any
  private nodeStatusList: any[]
  private _graphData: any
  private gatewayConditions: any[] // 新增：网关条件数据

  constructor(processInstance?: any, nodeStatusList?: any[], graphData?: any, gatewayConditions?: any[]) {
    this._processInstance = processInstance
    this.nodeStatusList = nodeStatusList || []
    this._graphData = graphData
    this.gatewayConditions = gatewayConditions || []
  }

  /**
   * 更新流程实例数据
   */
  updateProcessInstance(processInstance: any) {
    this._processInstance = processInstance
  }

  /**
   * 更新节点状态列表
   */
  updateNodeStatusList(nodeStatusList: any[]) {
    this.nodeStatusList = nodeStatusList
    console.log('ProcessStatusStyleManager - 节点状态列表已更新:', {
      count: nodeStatusList?.length || 0,
      data: nodeStatusList?.map(n => ({
        nodeId: n.nodeId,
        taskDefinitionKey: n.taskDefinitionKey,
        taskId: n.taskId,
        nodeName: n.nodeName,
        status: n.status
      }))
    })
  }

  /**
   * 更新流程图数据
   */
  updateGraphData(graphData: any) {
    this._graphData = graphData
  }

  /**
   * 更新网关条件数据
   */
  updateGatewayConditions(gatewayConditions: any[]) {
    this.gatewayConditions = gatewayConditions || []
    console.log('ProcessStatusStyleManager - 网关条件数据已更新:', {
      count: this.gatewayConditions.length,
      data: this.gatewayConditions
    })
  }

  /**
   * 根据节点ID获取节点状态
   */
  private getNodeStatus(nodeId: string): NodeStatus {
    if (!this.nodeStatusList || this.nodeStatusList.length === 0) {
      console.log(`getNodeStatus: 节点状态列表为空，节点ID: ${nodeId}`)
      return NodeStatus.PENDING
    }

    console.log(`getNodeStatus: 查找节点ID: ${nodeId}`)
    console.log(`getNodeStatus: 可用节点状态:`, this.nodeStatusList.map(n => ({
      nodeId: n.nodeId,
      taskDefinitionKey: n.taskDefinitionKey,
      taskId: n.taskId,
      nodeName: n.nodeName,
      status: n.status
    })))

    // 尝试多种方式匹配节点
    let nodeStatus = this.nodeStatusList.find(node => {
      // 1. 直接ID匹配
      if (node.nodeId === nodeId ||
        node.taskDefinitionKey === nodeId ||
        node.taskId === nodeId) {
        return true
      }

      // 2. 从taskDefinitionKey中提取节点类型进行匹配
      if (node.taskDefinitionKey) {
        const taskKey = node.taskDefinitionKey
        // 如果节点ID包含taskDefinitionKey中的关键部分，也认为是匹配
        if (nodeId.includes(taskKey) || taskKey.includes(nodeId)) {
          return true
        }
      }

      return false
    })

    // 如果通过ID没找到，尝试通过节点名称匹配
    if (!nodeStatus) {
      nodeStatus = this.nodeStatusList.find(node => {
        const nodeName = node.nodeName || node.taskName || ''
        return nodeName && nodeId.includes(nodeName) || nodeName.includes(nodeId)
      })
    }

    // 如果通过名称也没找到，尝试通过节点类型匹配
    if (!nodeStatus) {
      // 从节点ID推断节点类型
      if (nodeId === 'start') {
        // 开始节点通常已完成
        console.log(`getNodeStatus: 开始节点 ${nodeId} 推断为已完成状态`)
        return NodeStatus.COMPLETED
      } else if (nodeId === 'end') {
        // 结束节点通常未开始
        console.log(`getNodeStatus: 结束节点 ${nodeId} 推断为未开始状态`)
        return NodeStatus.PENDING
      } else if (nodeId.includes('gateway')) {
        // 网关节点根据流程状态判断
        const hasRunningTask = this.nodeStatusList.some(n => n.status === 'RUNNING' || n.status === 'ACTIVE')
        const status = hasRunningTask ? NodeStatus.WAITING : NodeStatus.PENDING
        console.log(`getNodeStatus: 网关节点 ${nodeId} 推断为 ${status} 状态`)
        return status
      }
    }

    if (!nodeStatus) {
      console.log(`getNodeStatus: 未找到节点状态，节点ID: ${nodeId}`)
      return NodeStatus.PENDING
    }

    console.log(`getNodeStatus: 找到节点状态:`, nodeStatus)

    // 根据节点状态映射到枚举值
    const statusMap: Record<string, NodeStatus> = {
      'COMPLETED': NodeStatus.COMPLETED,
      'RUNNING': NodeStatus.RUNNING,
      'PENDING': NodeStatus.PENDING,
      'WAITING': NodeStatus.WAITING,
      'SKIPPED': NodeStatus.SKIPPED,
      'CANCELLED': NodeStatus.CANCELLED,
      'CREATED': NodeStatus.PENDING,
      'ASSIGNED': NodeStatus.PENDING,
      // 新增：支持更多状态值
      'ACTIVE': NodeStatus.RUNNING,        // ACTIVE 状态映射到正在执行
      'SUSPENDED': NodeStatus.WAITING,     // SUSPENDED 状态映射到等待条件
      'TERMINATED': NodeStatus.CANCELLED   // TERMINATED 状态映射到已取消
    }

    const result = statusMap[nodeStatus.status] || NodeStatus.PENDING
    console.log(`getNodeStatus: 节点 ${nodeId} 状态: ${nodeStatus.status} -> ${result}`)
    return result
  }

  /**
   * 根据连线ID获取连线状态
   */
  private getEdgeStatus(sourceNodeId: string, targetNodeId: string): EdgeStatus {
    const sourceStatus = this.getNodeStatus(sourceNodeId)
    const targetStatus = this.getNodeStatus(targetNodeId)

    console.log(`getEdgeStatus: 连线 ${sourceNodeId} -> ${targetNodeId}`)
    console.log(`getEdgeStatus: 源节点状态: ${sourceStatus}, 目标节点状态: ${targetStatus}`)

    // 特殊处理：开始节点到第一个任务节点的连线
    if (sourceNodeId === 'start' && targetNodeId.includes('userTask')) {
      // 开始节点到第一个任务节点的连线应该显示为已完成状态
      console.log(`getEdgeStatus: 开始节点到第一个任务节点连线状态为已完成状态`)
      return EdgeStatus.COMPLETED
    }

    // 如果源节点已完成且目标节点正在执行，则连线为已完成状态
    if (sourceStatus === NodeStatus.COMPLETED && targetStatus === NodeStatus.RUNNING) {
      console.log(`getEdgeStatus: 连线状态为已完成状态 (已完成 -> 正在执行)`)
      return EdgeStatus.COMPLETED
    }

    // 如果源节点已完成且目标节点等待执行，则连线为已完成状态
    if (sourceStatus === NodeStatus.COMPLETED && targetStatus === NodeStatus.PENDING) {
      console.log(`getEdgeStatus: 连线状态为已完成状态 (已完成 -> 等待执行)`)
      return EdgeStatus.COMPLETED
    }

    // 如果源节点正在执行，则连线为激活状态
    if (sourceStatus === NodeStatus.RUNNING) {
      console.log(`getEdgeStatus: 连线状态为激活状态 (源节点正在执行)`)
      return EdgeStatus.ACTIVE
    }

    // 如果源节点已完成，则连线为已完成状态
    if (sourceStatus === NodeStatus.COMPLETED) {
      console.log(`getEdgeStatus: 连线状态为已完成状态 (源节点已完成)`)
      return EdgeStatus.COMPLETED
    }

    // 特殊处理：网关分支连线
    if (sourceNodeId.includes('gateway')) {
      // 网关分支连线需要根据条件判断是否激活
      const isActiveBranch = this.isGatewayBranchActive(sourceNodeId, targetNodeId)
      if (isActiveBranch) {
        // 如果分支激活，根据目标节点状态决定连线样式
        if (targetStatus === NodeStatus.RUNNING) {
          // 目标节点正在执行，连线为已完成状态（绿色实线）
          // 这样可以保持与主任审核到网关连线的一致性
          console.log(`getEdgeStatus: 网关分支连线状态为已完成状态 (目标节点正在执行，保持样式一致)`)
          return EdgeStatus.COMPLETED
        } else if (targetStatus === NodeStatus.COMPLETED) {
          // 目标节点已完成，连线为已完成状态（绿色实线）
          console.log(`getEdgeStatus: 网关分支连线状态为已完成状态 (目标节点已完成)`)
          return EdgeStatus.COMPLETED
        } else {
          // 目标节点等待执行，连线为激活状态（橙色虚线）
          console.log(`getEdgeStatus: 网关分支连线状态为激活状态 (目标节点等待执行)`)
          return EdgeStatus.ACTIVE
        }
      } else {
        // 分支非激活，连线为非激活状态（灰色虚线）
        console.log(`getEdgeStatus: 网关分支连线状态为非激活状态 (条件不满足)`)
        return EdgeStatus.INACTIVE
      }
    }

    console.log(`getEdgeStatus: 连线状态为等待状态 (默认)`)
    return EdgeStatus.PENDING
  }

  /**
   * 获取节点的状态样式
   */
  private getNodeStatusStyle(nodeId: string, nodeType: string): StatusStyleConfig {
    const status = this.getNodeStatus(nodeId)
    const baseStyle = NODE_STATUS_STYLES[status]
    const typeStyle = NODE_TYPE_DEFAULT_STYLES[nodeType] || {}

    // 合并基础状态样式和节点类型样式
    return {
      ...baseStyle,
      ...typeStyle
    }
  }

  /**
   * 获取连线的状态样式
   */
  private getEdgeStatusStyle(sourceNodeId: string, targetNodeId: string): EdgeStyleConfig {
    const status = this.getEdgeStatus(sourceNodeId, targetNodeId)
    return EDGE_STATUS_STYLES[status]
  }

  /**
   * 更新节点状态样式
   */
  updateNodeStatusStyles(nodes: any[]): any[] {
    if (!nodes || nodes.length === 0) {
      return nodes
    }

    return nodes.map(node => {
      const updatedNode = { ...node }

      // 确保style对象存在
      if (!updatedNode.style) {
        updatedNode.style = {}
      }

      // 获取节点状态样式
      const statusStyle = this.getNodeStatusStyle(node.id, node.type)

      // 应用状态样式
      updatedNode.style.backgroundColor = statusStyle.backgroundColor
      updatedNode.style.borderColor = statusStyle.borderColor
      updatedNode.style.color = statusStyle.color

      if (statusStyle.borderWidth) {
        updatedNode.style.borderWidth = statusStyle.borderWidth
      }

      if (statusStyle.borderStyle) {
        updatedNode.style.borderStyle = statusStyle.borderStyle
      }

      return updatedNode
    })
  }

  /**
   * 更新连线状态样式
   */
  updateEdgeStatusStyles(edges: any[]): any[] {
    if (!edges || edges.length === 0) {
      return edges
    }

    return edges.map(edge => {
      const updatedEdge = { ...edge }

      // 确保style对象存在
      if (!updatedEdge.style) {
        updatedEdge.style = {}
      }

      // 从连线ID中提取源节点和目标节点ID
      const edgeId = edge.id
      let sourceNodeId = ''
      let targetNodeId = ''

      // 解析连线ID格式：vueflow__edge-{source}-{target}
      if (edgeId.startsWith('vueflow__edge-')) {
        const parts = edgeId.replace('vueflow__edge-', '').split('-')
        if (parts.length >= 2) {
          sourceNodeId = parts[0]
          targetNodeId = parts[1]
        }
      }

      // 如果无法解析，尝试从source和target属性获取
      if (!sourceNodeId && !targetNodeId) {
        sourceNodeId = edge.source || edge.sourceNodeId
        targetNodeId = edge.target || edge.targetNodeId
      }

      if (sourceNodeId && targetNodeId) {
        // 获取连线状态样式
        const statusStyle = this.getEdgeStatusStyle(sourceNodeId, targetNodeId)

        // 应用状态样式
        updatedEdge.style.stroke = statusStyle.stroke
        updatedEdge.style.strokeWidth = statusStyle.strokeWidth
        updatedEdge.style.strokeDasharray = statusStyle.strokeDasharray
        updatedEdge.animated = statusStyle.animated
      } else {
        // 默认样式
        updatedEdge.style.stroke = '#d9d9d9'
        updatedEdge.style.strokeWidth = 2
        updatedEdge.style.strokeDasharray = '8,4'
        updatedEdge.animated = false
      }

      return updatedEdge
    })
  }

  /**
   * 更新整个流程图的状态样式
   */
  updateProcessStatusStyles(nodes: any[], edges: any[]): { nodes: any[], edges: any[] } {
    const updatedNodes = this.updateNodeStatusStyles(nodes)
    const updatedEdges = this.updateEdgeStatusStyles(edges)

    return {
      nodes: updatedNodes,
      edges: updatedEdges
    }
  }

  /**
   * 获取流程图的整体状态信息
   */
  getProcessStatusInfo(): {
    totalNodes: number
    completedNodes: number
    runningNodes: number
    pendingNodes: number
    progress: number
  } {
    if (!this.nodeStatusList || this.nodeStatusList.length === 0) {
      return {
        totalNodes: 0,
        completedNodes: 0,
        runningNodes: 0,
        pendingNodes: 0,
        progress: 0
      }
    }

    const totalNodes = this.nodeStatusList.length
    const completedNodes = this.nodeStatusList.filter(node =>
      node.status === 'COMPLETED'
    ).length
    const runningNodes = this.nodeStatusList.filter(node =>
      node.status === 'RUNNING'
    ).length
    const pendingNodes = this.nodeStatusList.filter(node =>
      node.status === 'PENDING' || node.status === 'WAITING'
    ).length

    const progress = totalNodes > 0 ? Math.round((completedNodes / totalNodes) * 100) : 0

    return {
      totalNodes,
      completedNodes,
      runningNodes,
      pendingNodes,
      progress
    }
  }

  /**
   * 判断网关分支是否激活
   */
  private isGatewayBranchActive(gatewayNodeId: string, targetNodeId: string): boolean {
    console.log(`isGatewayBranchActive: 判断网关 ${gatewayNodeId} 到 ${targetNodeId} 分支是否激活`)
    console.log(`isGatewayBranchActive: 当前网关条件数据:`, this.gatewayConditions)

    // 如果有网关条件数据，使用条件数据判断
    if (this.gatewayConditions && this.gatewayConditions.length > 0) {
      // 查找匹配的网关条件
      const gatewayCondition = this.gatewayConditions.find(condition => {
        const matches = condition.gatewayId === gatewayNodeId ||
                       condition.sourceNodeId === gatewayNodeId ||
                       gatewayNodeId.includes(condition.gatewayId) ||
                       condition.gatewayId.includes(gatewayNodeId)
        
        console.log(`isGatewayBranchActive: 检查网关条件匹配:`, {
          conditionGatewayId: condition.gatewayId,
          currentGatewayId: gatewayNodeId,
          matches: matches
        })
        
        return matches
      })

      if (gatewayCondition) {
        console.log(`isGatewayBranchActive: 找到网关条件:`, gatewayCondition)

        // 检查目标节点是否在激活的分支中
        const isActive = gatewayCondition.activeBranches &&
          gatewayCondition.activeBranches.some(branch => {
            const branchMatches = branch.targetNodeId === targetNodeId ||
                                 branch.targetNodeName === targetNodeId ||
                                 targetNodeId.includes(branch.targetNodeId) ||
                                 branch.targetNodeId.includes(targetNodeId)
            
            console.log(`isGatewayBranchActive: 检查分支匹配:`, {
              branchTargetId: branch.targetNodeId,
              branchTargetName: branch.targetNodeName,
              currentTargetId: targetNodeId,
              matches: branchMatches,
              conditionMet: branch.conditionMet
            })
            
            // 只有当前目标节点与分支目标节点匹配，且分支条件满足时，才认为是激活的
            return branchMatches && branch.conditionMet
          })

        console.log(`isGatewayBranchActive: 根据条件判断分支激活状态:`, isActive)
        return isActive
      } else {
        console.log(`isGatewayBranchActive: 未找到匹配的网关条件，网关ID: ${gatewayNodeId}`)
      }
    } else {
      console.log(`isGatewayBranchActive: 网关条件数据为空`)
    }

    // 如果没有条件数据或未找到匹配的条件，默认返回false
    console.log(`isGatewayBranchActive: 没有网关条件数据，默认分支非激活`)
    return false
  }

  /**
   * 重置所有样式为默认状态
   */
  resetToDefaultStyles(nodes: any[], edges: any[]): { nodes: any[], edges: any[] } {
    const resetNodes = nodes.map(node => ({
      ...node,
      style: {
        ...node.style,
        backgroundColor: '#ffffff',
        borderColor: '#d9d9d9',
        color: '#333333'
      }
    }))

    const resetEdges = edges.map(edge => ({
      ...edge,
      style: {
        ...edge.style,
        stroke: '#d9d9d9',
        strokeWidth: 2,
        strokeDasharray: '8,4'
      },
      animated: false
    }))

    return {
      nodes: resetNodes,
      edges: resetEdges
    }
  }
}

/**
 * 创建流程状态样式管理器的工厂函数
 */
export function createProcessStatusStyleManager(
  processInstance?: any,
  nodeStatusList?: any[],
  graphData?: any,
  gatewayConditions?: any[]
): ProcessStatusStyleManager {
  return new ProcessStatusStyleManager(processInstance, nodeStatusList, graphData, gatewayConditions)
}

/**
 * 默认导出
 */
export default ProcessStatusStyleManager
